package com.example.teaching_server.service;

import com.example.teaching_server.dto.TimelineItemDTO;
import com.example.teaching_server.entity.CheckInRecord;
import com.example.teaching_server.entity.CheckInImage;
import com.example.teaching_server.repository.CheckInRecordRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 时间线服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class TimelineService {

    private final CheckInRecordRepository recordRepository;

    /**
     * 获取时间线数据
     */
    public List<TimelineItemDTO> getTimelineData(Long activityId) {
        log.debug("获取时间线数据: activityId={}", activityId);

        validateActivityId(activityId);

        List<CheckInRecord> records = recordRepository.findRecordsWithImagesByActivityId(activityId);
        return records.stream()
                .map(this::convertToTimelineItemDTO)
                .collect(Collectors.toList());
    }

    /**
     * 获取课堂活动时间线
     */
    public List<TimelineItemDTO> getClassTimeline(Long classId) {
        log.debug("获取课堂时间线: classId={}", classId);

        validateClassId(classId);

        // TODO: 根据实际业务逻辑实现
        log.info("课堂时间线功能待实现: classId={}", classId);
        return List.of();
    }

    /**
     * 获取学生个人时间线
     */
    public List<TimelineItemDTO> getStudentTimeline(Long studentId) {
        log.debug("获取学生时间线: studentId={}", studentId);

        validateStudentId(studentId);

        // TODO: 根据实际业务逻辑实现
        log.info("学生时间线功能待实现: studentId={}", studentId);
        return List.of();
    }

    /**
     * 获取教师时间线
     */
    public List<TimelineItemDTO> getTeacherTimeline(Long teacherId) {
        log.debug("获取教师时间线: teacherId={}", teacherId);

        validateTeacherId(teacherId);

        // TODO: 根据实际业务逻辑实现
        log.info("教师时间线功能待实现: teacherId={}", teacherId);
        return List.of();
    }

    /**
     * 将打卡记录转换为时间线项DTO
     */
    private TimelineItemDTO convertToTimelineItemDTO(CheckInRecord record) {
        TimelineItemDTO.TimelineItemDTOBuilder builder = TimelineItemDTO.builder();

        builder.date(getCheckDateString(record))
                .time(getCheckTimeString(record))
                .activityName(getActivityName(record))
                .description(getDescription(record))
                .imageUrls(getImageUrls(record))
                .activityType("activity")
                .status("completed")
                .important(false)
                .completed(true);

        return builder.build();
    }

    /**
     * 获取打卡日期字符串
     */
    private String getCheckDateString(CheckInRecord record) {
        return record.getCheckDate() != null ? record.getCheckDate().toString() : "";
    }

    /**
     * 获取打卡时间字符串
     */
    private String getCheckTimeString(CheckInRecord record) {
        return record.getCheckTime() != null ? record.getCheckTime().toString() : "";
    }

    /**
     * 获取活动名称
     */
    private String getActivityName(CheckInRecord record) {
        return record.getActivity() != null && record.getActivity().getTitle() != null ?
                record.getActivity().getTitle() : "未知活动";
    }

    /**
     * 获取描述信息
     */
    private String getDescription(CheckInRecord record) {
        return record.getDescription() != null ? record.getDescription() : "";
    }

    /**
     * 获取图片URL列表
     */
    private List<String> getImageUrls(CheckInRecord record) {
        return record.getImages() != null ?
                record.getImages().stream()
                        .map(CheckInImage::getImageUrl)
                        .collect(Collectors.toList()) :
                List.of();
    }

    /**
     * 验证活动ID
     */
    private void validateActivityId(Long activityId) {
        if (activityId == null || activityId <= 0) {
            log.warn("活动ID无效: activityId={}", activityId);
            throw new IllegalArgumentException("活动ID无效");
        }
    }

    /**
     * 验证班级ID
     */
    private void validateClassId(Long classId) {
        if (classId == null || classId <= 0) {
            log.warn("班级ID无效: classId={}", classId);
            throw new IllegalArgumentException("班级ID无效");
        }
    }

    /**
     * 验证学生ID
     */
    private void validateStudentId(Long studentId) {
        if (studentId == null || studentId <= 0) {
            log.warn("学生ID无效: studentId={}", studentId);
            throw new IllegalArgumentException("学生ID无效");
        }
    }

    /**
     * 验证教师ID
     */
    private void validateTeacherId(Long teacherId) {
        if (teacherId == null || teacherId <= 0) {
            log.warn("教师ID无效: teacherId={}", teacherId);
            throw new IllegalArgumentException("教师ID无效");
        }
    }

    /**
     * 获取指定日期范围的时间线数据
     */
    public List<TimelineItemDTO> getTimelineDataByDateRange(Long activityId, String startDate, String endDate) {
        log.debug("获取日期范围时间线数据: activityId={}, startDate={}, endDate={}",
                activityId, startDate, endDate);

        validateActivityId(activityId);
        validateDateRange(startDate, endDate);

        // TODO: 根据实际业务逻辑实现日期范围查询
        log.info("日期范围时间线功能待实现: activityId={}, startDate={}, endDate={}",
                activityId, startDate, endDate);
        return List.of();
    }

    /**
     * 验证日期范围
     */
    private void validateDateRange(String startDate, String endDate) {
        if (startDate == null || startDate.trim().isEmpty()) {
            throw new IllegalArgumentException("开始日期不能为空");
        }
        if (endDate == null || endDate.trim().isEmpty()) {
            throw new IllegalArgumentException("结束日期不能为空");
        }
    }

    /**
     * 获取用户的时间线数据（按用户ID和活动类型）
     */
    public List<TimelineItemDTO> getUserTimelineByType(Long userId, String activityType) {
        log.debug("获取用户按类型时间线: userId={}, activityType={}", userId, activityType);

        validateUserId(userId);
        validateActivityType(activityType);

        log.info("按类型时间线功能待实现: userId={}, activityType={}", userId, activityType);
        return List.of();
    }

    /**
     * 验证用户ID
     */
    private void validateUserId(Long userId) {
        if (userId == null || userId <= 0) {
            log.warn("用户ID无效: userId={}", userId);
            throw new IllegalArgumentException("用户ID无效");
        }
    }

    /**
     * 验证活动类型
     */
    private void validateActivityType(String activityType) {
        if (activityType == null || activityType.trim().isEmpty()) {
            throw new IllegalArgumentException("活动类型不能为空");
        }
    }

    /**
     * 检查时间线数据是否存在（修正版 - 使用现有方法）
     */
    public boolean existsTimelineData(Long activityId) {
        log.debug("检查时间线数据是否存在: activityId={}", activityId);

        validateActivityId(activityId);

        try {
            // 使用现有的 findRecordsWithImagesByActivityId 方法来判断
            List<CheckInRecord> records = recordRepository.findRecordsWithImagesByActivityId(activityId);
            return !records.isEmpty();
        } catch (Exception e) {
            log.error("检查时间线数据失败: activityId={}", activityId, e);
            return false;
        }
    }

    /**
     * 获取时间线数据统计信息（修正版 - 基于现有方法实现）
     */
    public TimelineStatistics getTimelineStatistics(Long activityId) {
        log.debug("获取时间线统计信息: activityId={}", activityId);

        validateActivityId(activityId);

        try {
            List<CheckInRecord> records = recordRepository.findRecordsWithImagesByActivityId(activityId);

            int totalRecords = records.size();
            int totalImages = calculateTotalImages(records);
            int uniqueDays = calculateUniqueDays(records);

            return new TimelineStatistics(totalRecords, totalImages, uniqueDays);
        } catch (Exception e) {
            log.error("获取时间线统计信息失败: activityId={}", activityId, e);
            return new TimelineStatistics(0, 0, 0);
        }
    }

    /**
     * 计算总图片数量
     */
    private int calculateTotalImages(List<CheckInRecord> records) {
        return records.stream()
                .mapToInt(record -> record.getImages() != null ? record.getImages().size() : 0)
                .sum();
    }

    /**
     * 计算唯一日期数量
     */
    private int calculateUniqueDays(List<CheckInRecord> records) {
        return (int) records.stream()
                .map(CheckInRecord::getCheckDate)
                .distinct()
                .count();
    }

    /**
     * 获取唯一打卡日期列表
     */
    public List<String> getDistinctCheckDates(Long activityId) {
        log.debug("获取唯一打卡日期列表: activityId={}", activityId);

        validateActivityId(activityId);

        try {
            List<CheckInRecord> records = recordRepository.findRecordsWithImagesByActivityId(activityId);
            return records.stream()
                    .map(this::getCheckDateString)
                    .distinct()
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取打卡日期列表失败: activityId={}", activityId, e);
            return List.of();
        }
    }

    /**
     * 时间线统计信息内部类
     *
     * @param totalRecords Getters
     */
        public record TimelineStatistics(int totalRecords, int totalImages, int uniqueDays) {

    }
}
